<template>
  <div v-loading="loading" element-loading-text="加载中">
    <el-form ref="materialForm" :model="materialForm" :rules="materialRules" label-width="100px" label-suffix="：">
      <el-form-item label="文件夹" prop="folderId">
        <el-cascader v-model="materialForm.folderId"
          :props="{ checkStrictly: true, value: 'folderId', label: 'folderName', children: 'children', emitPath: false }"
          :options="folderList"
          filterable
          clearable
          class="width-300"
        >
        </el-cascader>
      </el-form-item>

      <el-form-item label="素材文件" prop="materialSystemUrl">
        <el-upload list-type="picture-card" 
          style="display: inline-block"
          action="/api/common/uploadFiles"
          name="files" 
          v-loading="fileLoading" 
          :data="token" 
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload">

          <template v-if="materialForm.materialSystemUrl">
            <img v-if="materialType === 1" :src="materialForm.materialSystemUrl + '?imageView2/1/w/200/h/200/q/100'" class="picture">
            <video v-else controls="controls" 
              class="video"
              :src="materialForm.materialSystemUrl">
              <source type="video/mp4">
              Your browser does not support the video tag.
            </video>
          </template>

          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div v-if="materialForm.materialSystemUrl" class="mar-l-10 cursor-p" style="display: inline-block" @click="doClearMaterial()">
          <svg-icon v-if="materialForm.materialSystemUrl" icon-class="close" class="icon font-16 noraml-hide active"/>
        </div>
      </el-form-item>

      <el-form-item label="素材名称" prop="materialName">
        <el-input v-model="materialForm.materialName" 
          maxlength="20" 
          class="width-300 m-n" 
          :disabled="!materialForm.materialSystemUrl"
          show-word-limit>

          <template slot="append">{{ materialForm.ext }}</template>
        </el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doConfirm">确定</el-button>
      <el-button @click="doCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import { doUploadMaterial } from '@/api/third/thirdMaterial'

  export default {
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      },
      // 平台类型
      platformType: {
        type: Number,
        required: true
      },
      // 店铺id
      shopId: {
        type: String,
        required: true
      },
      // 素材类型
      materialType: {
        type: Number,
        required: true
      },
      // 当前文件夹id
      currentFolderId: {
        type: String
      },
      // 文件夹列表
      folderList: {
        type: Array,
        required: true
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.init()
        }
      }
    },
    data() {
      return {
        token: {},
        // 素材表单
        materialForm: {
          folderId: '',
          materialType: '',
          materialName: '',
          materialSystemUrl: '',
          ext: ''
        },
        // 素材表单规则
        materialRules: {
          folderId: [
            { required: true, trigger: 'blur', message: '请选择文件夹' }
          ],
          materialSystemUrl: [
            { required: true, trigger: 'blur', message: '素材文件不能为空' }
          ],
          materialName: [
            { required: true, trigger: 'blur', message: '素材名称不能为空' }
          ]
        },
        loading: false,
        fileLoading: false
      }
    },
    created() {
      this.token = { accessToken: getToken() }
      this.init()
    },
    methods: {
      init() {
        const originData = this.$options.data()
        this.materialForm = originData.materialForm
        if (this.$refs['materialForm']) {
          this.$refs['materialForm'].clearValidate()
        }
        if (this.currentFolderId && this.currentFolderId !== '0') {
          this.materialForm.folderId = this.currentFolderId
        }
      },
      // 图片上传前校验
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpg'
        const isJPEG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isMP4 = file.type === 'video/mp4'
        if (this.materialType === 1) {
          if (!isJPG && !isJPEG && !isPNG) {
            this.$message.error('上传图片必须是JPG/JPEG/PNG格式')
            return false
          }
          if ((3 * 1024 * 1024) < file.size) {
            this.$message.error('上传图片大小不能超过3M')
            return false
          }
        } else {
          if (!isMP4) {
            this.$message.error('上传视频必须是MP4格式')
            return false
          }
        }
        this.fileLoading = true
        return true
      },
      // 图片上传成功后处理
      handleUploadSuccess(res, file, fileList) {
        this.fileLoading = false
        if (res.code === 101) {
          const fileName = file.name
          const fileSize = file.size
          const imageUrl = res.data[0]

          if (this.materialType === 1) {
            const image = new Image()
            image.src = imageUrl
            image.onload = () => {
              this.materialForm.materialWidth = image.width
              this.materialForm.materialHeight = image.height
            }
          }
          this.materialForm.materialSystemUrl = imageUrl
          this.materialForm.materialName = fileName.substr(0, fileName.lastIndexOf('.') > 20 ? 19 : fileName.lastIndexOf('.'))
          this.materialForm.ext = fileName.substr(fileName.lastIndexOf('.') + 1, fileName.length)
          // KB
          this.materialForm.materialSize = (fileSize / 1024).toFixed(1)
          this.$refs['materialForm'].validateField(['materialSystemUrl', 'materialName'])
        } else {
          this.$message({ type: 'error', message: res.msg })
        }
      },
      // 清空素材
      doClearMaterial() {
        this.materialForm.materialSystemUrl = ''
        this.materialForm.materialName = ''
        this.materialForm.ext = ''
        this.materialForm.materialWidth = ''
        this.materialForm.materialHeight = ''
        this.materialForm.materialSize = ''
      },
      // 确定事件
      doConfirm() {
        this.$refs['materialForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            const form = {
              platformType: this.platformType,
              shopId: this.shopId,
              materialType: this.materialType,
              folderId: this.materialForm.folderId,
              materialName: this.materialForm.materialName + '.' + this.materialForm.ext,
              materialSystemUrl: this.materialForm.materialSystemUrl,
              materialSize: this.materialForm.materialSize,
              materialWidth: this.materialForm.materialWidth,
              materialHeight: this.materialForm.materialHeight
            }
            doUploadMaterial(form).then((response) => {
              this.loading = false
              if (response.isError) return
              this.$message({ type: 'success', message: '上传成功' })
              this.$emit('callback', true)
            })
          }
        })
      },
      // 取消事件
      doCancel() {
        this.$emit('callback', false)
      }
    }
  }
</script>

<style lang="less" scoped>
  .m-n {
    /deep/ .el-input__inner {
      padding-right: 50px;
    }
    /deep/ .el-input-group__append {
      padding: 0 10px;
    }
    
  }
  .picture {
    width: 146px;
    height: 146px;
    display: block;
  }
  .video {
    width: 260px;
    height: 146px;
    display: block;
  }
</style>